﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CosmosKernel4.UI.Login
{
    class Login
    {
        
        public void do_login()
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            GruntyOS.HAL.StorageDevice filesys = GruntyOS.HAL.FileSystem.Root;
            string[] lines = CosmosKernel4.Global.StringManip.GetString(filesys.readFile("/plasmid/passwd")).Split('\n'); //In-situ parse as for some reason Passwd.ParsePasswd is fucked up, some interface crap
            // As it appears lists are messed up... List<String> l = new List<string>();
            String[] l = new String[lines.Length];
            //OK, 
            for(int i = 0; i < lines.Length; i++)
            {
                string line = lines[i]; 
                int index = CosmosKernel4.Global.StringManip.GetNthIndex(line, ':', 2);
                string st = line.Remove(index);
                l[i] = st; 
            }


            
            Console.WriteLine("Plasmid OS 0.2 Login. Type SETUP to access install utility or log in");
        main:
            Console.Write("Username:");
            string uname = Console.ReadLine();
            if (uname == "SETUP")
            {
                CosmosKernel4.Install.plasmidInstall ins = new CosmosKernel4.Install.plasmidInstall();
                ins.Install();
            }
            Console.Write("Password:");
            
            byte[] pass = new Plasmid.Crypto.MD5.MD5().ComputeHash(CosmosKernel4.Global.StringManip.GetBytes(Console.ReadLine()));
            string hash = CosmosKernel4.Global.StringManip.stripchar(BitConverter.ToString(pass).ToLowerInvariant(), '-');
            //Warning: Do not read the next line for your own mental health - all it does is creates a string of username:md5(password)
            string log = uname + ":" + hash;
            
            for (int i = 0; i < l.Length; i++)
            {
                if (l[i] == log)
                {
                    GruntyOS.CurrentUser.Username = uname;
                    new CosmosKernel4.UI.Shell.PLSMSH().do_plsmsh();
                }
            }
            

        goto main;
                
        }
    }
}
